﻿var jXSocketsWorker = function () {
    var n = new Worker("/scripts/jXSocketsWorker.WebSocket.js");
    var callbacks = {};
    n.onmessage = function (evt) {
        raiseEvent(evt)
    }    
    var raiseEvent = function (message) {
        var event_name;
        
        if (typeof message.data === "string") {
            var msg = JSON.parse(message.data);
            event_name = msg.event;
            dispatch(event_name, msg.data);
        } else {
            dispatch("blob", message.data);
        }
    };

    this.connect = function (_url) {
        var o = {
            method: "open",
            settings: {
                url: _url
            }
        };
        n.postMessage(o)
    }
    this.trigger = function (_name, _data) {
        var o = {
            method: "send",
            message: {
                event: _name,
                data: _data
            }
        }
        n.postMessage(o);
    }
    this.bind = function (event_name, callback) {
        callbacks[event_name] = callbacks[event_name] || [];
        callbacks[event_name].push({
            callback: callback,
            options: null
        });
    }

    var dispatch = function (event_name, message) {
        var chain = callbacks[event_name];
        if (typeof chain == 'undefined') return;
        for (var i = 0; i < chain.length; i++) {
            chain[i].callback(message);
            var opts = chain[i].options;
            if (opts != null) {
                if (opts.Counter !== undefined) {
                    chain[i].options.Counter.Messages--;
                    if (chain[i].options.Counter.Messages == 0) {
                        if (typeof opts.Counter.Completed !== 'undefined') {
                            opts.Counter.Completed();
                        }
                    }
                }
            }
        }
    }
}